package com.jiang.mybatis_plus.filter;

import com.jiang.core.common.AppException;
import com.jiang.core.common.MSG;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;


@Slf4j
@ControllerAdvice
public class AppControllerAdvice {

    @InitBinder
    public void initBinder(WebDataBinder binder) {}

    @ResponseBody
    @ExceptionHandler(value = AppException.class)
    public MSG<?> exceptionHandler(AppException e) {
        log.error("AppException:", e);
        return MSG.ERROR(-1000, e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public MSG<?> errorHandler(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException:", e);
        return MSG.ERROR(-1000, e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public MSG<?> errorHandler(Exception ex) {
        log.error("Exception:", ex);
        return MSG.ERROR(500, ex.getMessage());
    }
}
